﻿package cn.com.truelore;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.ksoap2.serialization.SoapObject;

import cn.com.truelore.R;
import cn.com.truelore.adapter.TabContentSettingStep1Adapter;
import cn.com.truelore.adapter.TabContentSettingStep2Adapter;
import cn.com.truelore.adapter.TabContentSettingStep3Adapter;
import cn.com.truelore.adapter.ViewHolderSettingStep2;
import cn.com.truelore.adapter.ViewHolderSettingStep3;
import cn.com.truelore.adapter.ViewHolderStetingStep1;
import cn.com.truelore.base.BaseActivity;
import cn.com.truelore.common.CommonAlertDialog;
import cn.com.truelore.common.Constants;
import cn.com.truelore.service.GfoWebService;
import cn.com.truelore.service.WebServiceThread;
import cn.com.truelore.vo.SettingStep1VO;
import cn.com.truelore.vo.SettingStep2VO;
import cn.com.truelore.vo.SettingStep3VO;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class TabContentSettingActivity extends BaseActivity {

	private List<SettingStep1VO> _dataList1;

	private String _strSettingStep1SaveSP = null;
	private ListView _listviewSettingStep1 = null;
	private List<SettingStep2VO> _dataList2;
	private String _strSettingStep2SaveSP = null;
	private ListView _listviewSettingStep2 = null;

	private List<SettingStep3VO> _dataList3;
	private ViewFlipper mViewFlipper;
	Handler _handlerWebService = null;
	ProgressDialog _progressDialog = null;
	/**
	 * Web Service
	 */
	private WebServiceThread _webServiceThread = null;

	public TabContentSettingActivity() {
		super(R.layout.tab_context_setting);
	}

	public void initPageData() {
		super.initPageData();
		try {
			mViewFlipper = (ViewFlipper) findViewById(R.id.viewFlipperSetting);
			mViewFlipper.setOnTouchListener(this);
			mViewFlipper.setLongClickable(true);
			_dataList2 = new ArrayList<SettingStep2VO>();
			_dataList3 = new ArrayList<SettingStep3VO>();
			initListView1();
		} catch (Exception ex) {
			Toast.makeText(getApplicationContext(), ex.getMessage(),
					Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 初始化页面按钮点击事件
	 */
	public void initButtonClick() {
		ImageButton imageBtn = (ImageButton) findViewById(R.id.imgBtnSettingStepNext1);

		imageBtn.setOnClickListener(new ImageButton.OnClickListener() {
			public void onClick(View v) {
				imgBtnSettingStepNext1_onClick(v);
			}

		});
		imageBtn = (ImageButton) findViewById(R.id.imgBtnSettingStepNext2);
		imageBtn.setOnClickListener(new ImageButton.OnClickListener() {
			public void onClick(View v) {
				imgBtnSettingStepNext2_onClick(v);
			}
		});

		imageBtn = (ImageButton) findViewById(R.id.imgBtnSettingStepNext3);
		imageBtn.setOnClickListener(new ImageButton.OnClickListener() {
			public void onClick(View v) {
				imgBtnSettingStepNext3_onClick(v);
			}
		});

		imageBtn = (ImageButton) findViewById(R.id.imgBtnSettingStepNext4);
		imageBtn.setOnClickListener(new ImageButton.OnClickListener() {
			public void onClick(View v) {
				imgBtnSettingStepNext4_onClick(v);
			}
		});
	}

	private void imgBtnSettingStepNext1_onClick(View v) {

		boolean flg = false;
		String strIds = "";
		if (_dataList1 != null) {
			for (SettingStep1VO vo : _dataList1) {
				if (vo.getStatus() == 1) {
					if (flg == true)
						strIds = strIds + ",";
					strIds = strIds + vo.getRId();
					flg = true;
				}
			}
		}
		if (flg == true) {
			super.setSharedPreferences(Constants.SP_SETTING,
					Constants.SP_SETTING_STEP1, strIds);
			mViewFlipper.showNext();
			initListView2();

		} else {
			CommonAlertDialog.ShowAlertInfo(this,
					"Please select at least one location.");
		}
	}

	private void imgBtnSettingStepNext2_onClick(View v) {
		boolean flg = false;
		String strIds = "";
		if (_dataList2 != null) {
			for (SettingStep2VO vo : _dataList2) {
				if (vo.getStatus() == 1) {
					if (flg == true)
						strIds = strIds + ",";
					strIds = strIds + vo.getCtID();
					flg = true;
				}
			}
		}
		if (flg == true) {
			super.setSharedPreferences(Constants.SP_SETTING,
					Constants.SP_SETTING_STEP2, strIds);
			this.initListView3();
			mViewFlipper.showNext();
		} else {
			CommonAlertDialog.ShowAlertInfo(this,
					"Please select at least one location.");
		}
	}

	private void imgBtnSettingStepNext3_onClick(View v) {
		boolean flg = false;
		String strIds = "";
		for (SettingStep3VO vo : _dataList3) {
			if (vo.getStatus() == 1) {
				if (flg == true)
					strIds = strIds + ",";
				strIds = strIds + vo.getRId();
				flg = true;
			}
		}
		if (flg == true) {
			super.setSharedPreferences(Constants.SP_SETTING,
					Constants.SP_SETTING_STEP3, strIds);
			EditText editText = (EditText) findViewById(R.id.editTextSettingStep4BrokerName);
			editText.setText(super.getSharedPreferences(Constants.SP_SETTING,
					Constants.BROKERNAME));
			editText = (EditText) findViewById(R.id.editTextSettingStep4BrokerPhoneNumber);
			editText.setText(super.getSharedPreferences(Constants.SP_SETTING,
					Constants.BROKERPHONE));
			mViewFlipper.showNext();
		} else {
			CommonAlertDialog.ShowAlertInfo(this,
					"Please select at least one location.");
		}
	}

	private void imgBtnSettingStepNext4_onClick(View v) {
		EditText editText = (EditText) findViewById(R.id.editTextSettingStep4BrokerName);
		super.setSharedPreferences(Constants.SP_SETTING, Constants.BROKERNAME,
				editText.getText().toString());
		editText = (EditText) findViewById(R.id.editTextSettingStep4BrokerPhoneNumber);
		super.setSharedPreferences(Constants.SP_SETTING, Constants.BROKERPHONE,
				editText.getText().toString());

		// 设置已经完成内容
		super.setSharedPreferences(Constants.SP_SETTING,
				Constants.SP_SETTING_STEP4, Constants.SP_SETTING_STEP4_COMPLETE);
		// start new intent
		/*
		 * Intent intent = new Intent(this, HomeActivity.class);
		 * super.startActivity(intent);
		 */
		this.finish();
		// mViewFlipper.showNext();
	}

	private void initListView1() {
		_strSettingStep1SaveSP = super.getSharedPreferences(
				Constants.SP_SETTING, Constants.SP_SETTING_STEP1);
		_listviewSettingStep1 = (ListView) findViewById(R.id.listviewSettingStep1);
		_handlerWebService = new Handler() {
			public void handleMessage(Message message) {
				_dataList1 = new ArrayList<SettingStep1VO>();
				Bundle bundler = message.getData();
				if (bundler == null
						|| StringUtils.isBlank(bundler.getString("error")) == false) {
					showErrorNetWork();
					return;
				}
				ArrayList<String> strArrayList = null;
				SettingStep1VO addVO = null;
				String[] strListSP = StringUtils.split(_strSettingStep1SaveSP,
						",");
				for (int i = 0; i < bundler.size(); i++) {
					strArrayList = bundler
							.getStringArrayList(String.valueOf(i));
					addVO = new SettingStep1VO(strArrayList);
					for (String strId : strListSP) {
						if (addVO.getRId().equals(strId) == true) {
							addVO.setStatus(1);
						}
					}
					_dataList1.add(addVO);
				}
				TabContentSettingStep1Adapter adapter = new TabContentSettingStep1Adapter(
						TabContentSettingActivity.this, _dataList1);
				_listviewSettingStep1.setAdapter(adapter);
				_listviewSettingStep1.setItemsCanFocus(false);
				_listviewSettingStep1
						.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
				_listviewSettingStep1
						.setOnItemClickListener(new OnItemClickListener() {
							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id) {
								ViewHolderStetingStep1 vHollder = (ViewHolderStetingStep1) view
										.getTag();
								vHollder.cBox.toggle();
								saveStatusSettingStep1(position,
										vHollder.cBox.isChecked());
							}
						});

				_progressDialog.cancel();
				_progressDialog.dismiss();
			}
		};

		_progressDialog = ProgressDialog.show(TabContentSettingActivity.this,
				super.getResources().getString(R.string.app_name), super
						.getResources().getString(R.string.loading), true);
		try {
			_webServiceThread = new WebServiceThread(_handlerWebService,
					Constants.OP_REGIONLIST, new String[] { "RID", "RNm" });
			_webServiceThread.doStart();
		} catch (Exception ex) {
			_progressDialog.dismiss();
		}
	}

	private void showErrorNetWork() {
		_progressDialog.cancel();
		_progressDialog.dismiss();
		showAlertInfo(this.getResources().getString(R.string.errornetwork),
				true);
		// this.finish();
	}

	private void initListView2() {
		// 获取城市列表
		_strSettingStep1SaveSP = super.getSharedPreferences(
				Constants.SP_SETTING, Constants.SP_SETTING_STEP1);
		_strSettingStep2SaveSP = super.getSharedPreferences(
				Constants.SP_SETTING, Constants.SP_SETTING_STEP2);
		_listviewSettingStep2 = (ListView) findViewById(R.id.listviewSettingStep2);

		_handlerWebService = new Handler() {
			public void handleMessage(Message message) {
				_dataList2 = new ArrayList<SettingStep2VO>();
				Bundle bundler = message.getData();
				if (bundler == null
						|| StringUtils.isBlank(bundler.getString("error")) == false) {
					showErrorNetWork();
					return;
				}
				ArrayList<String> strArrayList = null;
				SettingStep2VO addVO = null;
				String[] strListSP = StringUtils.split(_strSettingStep2SaveSP,
						",");
				String strRNm = "";
				String soapRNm = "";
				for (int i = 0; i < bundler.size(); i++) {
					strArrayList = bundler
							.getStringArrayList(String.valueOf(i));
					addVO = new SettingStep2VO(strArrayList);
					for (String strId : strListSP) {
						if (addVO.getCtID().equals(strId) == true) {
							addVO.setStatus(1);
						}
					}
					soapRNm = addVO.getRNm();
					// 表示标题行的数据
					if (strRNm.equals(soapRNm) == false) {
						SettingStep2VO titleVO = new SettingStep2VO();
						strRNm = soapRNm;
						titleVO.setType(-1);
						titleVO.setCtNm(soapRNm);
						_dataList2.add(titleVO);
					}
					_dataList2.add(addVO);
				}
				TabContentSettingStep2Adapter adapter = new TabContentSettingStep2Adapter(
						TabContentSettingActivity.this, _dataList2);
				_listviewSettingStep2.setAdapter(adapter);
				_listviewSettingStep2.setItemsCanFocus(false);
				_listviewSettingStep2
						.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
				_listviewSettingStep2
						.setOnItemClickListener(new OnItemClickListener() {
							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id) {
								ViewHolderSettingStep2 vHollder = (ViewHolderSettingStep2) view
										.getTag();
								// 在每次获取点击的item时将对于的checkbox状态改变，同时修改map的值。
								if (vHollder.cBox != null) {
									vHollder.cBox.toggle();
									saveStatusSettingStep2(position,
											vHollder.cBox.isChecked());
								}
							}
						});

				_progressDialog.cancel();
				_progressDialog.dismiss();
			}
		};
		_progressDialog = ProgressDialog.show(TabContentSettingActivity.this,
				super.getResources().getString(R.string.app_name), super
						.getResources().getString(R.string.loading), true);
		try {
			_webServiceThread = new WebServiceThread(_handlerWebService,
					Constants.OP_CITYLIST, new String[] { "rids" },
					new String[] { _strSettingStep1SaveSP }, new String[] {
							"RNm", "CtID", "CtNm" });
			_webServiceThread.doStart();
		} catch (Exception ex) {
			_progressDialog.dismiss();
		}

	}

	private void initListView3() {
		// 获取城市列表
		String strWheatTypes = super.getSharedPreferences(Constants.SP_SETTING,
				Constants.SP_SETTING_STEP3);
		_dataList3 = new ArrayList<SettingStep3VO>();
		/*
		 * SharedPreferences sp = super.getSharedPreferences(
		 * Constants.SP_WHEATTYPE, 0);
		 */
		/* Map<String, String> map = (Map<String, String>) sp.getAll(); */
		Map<String, String> map = new LinkedHashMap<String, String>();
		map.put("3", "2011 HRW");
		map.put("5", "2011 SRW");
		map.put("7", "2011 SWW");
		map.put("9", "2011 HRS");
		map.put("4", "2012 HRW");
		map.put("6", "2012 SRW");
		map.put("8", "2012 SWW");
		map.put("10", "2012 HRS");

		Set<Map.Entry<String, String>> set = map.entrySet();
		Map.Entry<String, String> entry;
		SettingStep3VO addVO = null;
		String[] listWheatType = StringUtils.split(strWheatTypes, ",");
		for (Iterator<Map.Entry<String, String>> it = set.iterator(); it
				.hasNext();) {
			entry = (Map.Entry<String, String>) it.next();
			addVO = new SettingStep3VO();
			addVO.setRId(entry.getKey());
			addVO.setTitle(entry.getValue());
			for (String value : listWheatType) {
				if (entry.getKey().equals(value) == true) {
					addVO.setStatus(1);
					break;
				}
			}
			_dataList3.add(addVO);
		}

		ListView list = (ListView) findViewById(R.id.listviewSettingStep3);
		TabContentSettingStep3Adapter adapter = new TabContentSettingStep3Adapter(
				this, _dataList3);
		list.setAdapter(adapter);
		list.setItemsCanFocus(false);
		list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		list.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ViewHolderSettingStep3 vHollder = (ViewHolderSettingStep3) view
						.getTag();
				// 在每次获取点击的item时将对于的checkbox状态改变，同时修改map的值。
				vHollder.cBox.toggle();
				saveStatusSettingStep3(position, vHollder.cBox.isChecked());
			}
		});
	}

	private void saveStatusSettingStep1(int position, boolean checkStatus) {
		if (_dataList1 != null && _dataList1.size() > position) {
			SettingStep1VO vo = _dataList1.get(position);
			// 重新设定状态
			if (checkStatus == true) {
				vo.setStatus(1);
			} else {
				vo.setStatus(0);
			}
		}
	}

	private void saveStatusSettingStep2(int position, boolean checkStatus) {
		if (_dataList2 != null && _dataList2.size() > position) {
			SettingStep2VO vo = _dataList2.get(position);
			// 重新设定状态
			if (checkStatus == true) {
				vo.setStatus(1);
			} else {
				vo.setStatus(0);
			}
		}
	}

	private void saveStatusSettingStep3(int position, boolean checkStatus) {
		if (_dataList3 != null && _dataList3.size() > position) {
			SettingStep3VO vo = _dataList3.get(position);
			// 重新设定状态
			if (checkStatus == true) {
				vo.setStatus(1);
			} else {
				vo.setStatus(0);
			}
		}
	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float arg3) {
		if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
				&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
			mViewFlipper.showPrevious();
		}
		return false;
	}

	/**
	 * 返回按钮判断
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 判断是否按下了返回按钮
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			int id = mViewFlipper.getCurrentView().getId();
			if (R.id.linearLayoutSettingView1 != id) {
				mViewFlipper.showPrevious();
				return true;
			}
		}
		return false;
	}

	public void onDestroy() {
		if (_webServiceThread != null) {
			_webServiceThread.doDispose();
		}
		super.onDestroy();
	}

}
